package com.sumainfor.pc.gmio.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.PageUtils;
import com.sumainfor.common.utlis.Pager;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.SeBillOutlayMapper;
import com.sumainfor.pc.gmio.dao.SeEleMeterMapper;
import com.sumainfor.pc.gmio.dao.SeTenantBillMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.service.SeEleMeterService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 */
@Service
public class SeEleMeterSerivceImpl implements SeEleMeterService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log= LoggerFactory.getLogger(SeEleMeterSerivceImpl.class);
    @Autowired
    private SeEleMeterMapper seEleMeterMapper;
    @Autowired
    private SeTenantBillMapper seTenantBillMapper;
    @Autowired
    private SeBillOutlayMapper seBillOutlayMapper;
    @Autowired
    private ZpcMktFeign zpcMktFeign;
    @Autowired
    private UtilsMapper utilsMapper;

    /**
     * 查询电表录入记录的列表
     * @param params
     * @return
     */
    @Override
    public JsonResult getEleMeterList(Map<String,Object>params) {
        Pager pager=new Pager();
        pager.setPageno(Integer.parseInt(params.get("pageno").toString()));
        pager.setPagesize(Integer.parseInt(params.get("pagesize").toString()));
        pager.setPagerNecessary(params, pager);
        JsonResult result=new JsonResult();
        PageUtils pageUtils = new PageUtils();
        String a="";
        if(params.get("ifGenerate")!=null){
            a=params.get("ifGenerate").toString();
        }
        if (a.equals("")){//是否已录入
            //查询运营部的电表录入记录
            List<Map<String,Object>> list=seEleMeterMapper.getEleMeterList(params);
            //查询市场部的房源详表信息
            result=zpcMktFeign.getHouInfoListForEwg(params);
            if (result.get("errorCode").equals("0")) {
                Map<String,Object>map=(Map<String,Object>)result.get("result");
                //市场部的房源列表
                List<Map<String,Object>> mktlist=(List<Map<String,Object>>)map.get("dataList");
                for (Map<String,Object> giomap : list){
                    for (Map<String,Object> mktmap : mktlist) {
                        if (MapUtils.getString(giomap, "HouId").equals(MapUtils.getString(mktmap, "HouId"))) {
                            giomap.remove("HouId",null);
                            giomap.remove("HouInfoId",null);
                            mktmap.putAll(giomap);
                        }
                    }
                }
            }
        }else{
            String [] genList=a.split(",");
            if (genList.length>1){
                //查询运营部的电表录入记录
                List<Map<String,Object>> list=seEleMeterMapper.getEleMeterList(params);

                //查询市场部的房源详表信息
                result=zpcMktFeign.getHouInfoListForEwg(params);
                if (result.get("errorCode").equals("0")) {
                    Map<String,Object>map=(Map<String,Object>)result.get("result");
                    //市场部的房源列表
                    List<Map<String,Object>> mktlist=(List<Map<String,Object>>)map.get("dataList");
                    for (Map<String,Object> giomap : list){
                        for (Map<String,Object> mktmap : mktlist) {
                            if (MapUtils.getString(giomap, "HouId").equals(MapUtils.getString(mktmap, "HouId"))) {
                                giomap.remove("HouId",null);
                                giomap.remove("HouInfoId",null);
                                mktmap.putAll(giomap);
                            }
                        }
                    }
                }
            }else{
                String num=genList[0];
                System.out.println("参数:"+num);
                if (num.equals("1")){//查询已录入
                    //保存已录入的记录
                    List<Map<String,Object>> gmioList=new ArrayList<Map<String,Object>>();
                    //查询运营部的电表录入记录
                    List<Map<String,Object>> list=seEleMeterMapper.getEleMeterList(params);
                    if (list.size()>0){
                        List<String> eidList=new ArrayList<String>();
                        for (Map<String,Object> eleMap:list){
                            if(eleMap.get("HouId")!=null){
                                eidList.add(eleMap.get("HouId").toString());
                            }
                        }
                        params.put("eidList",eidList);
                        //查询市场部的房源详表信息
                        result=zpcMktFeign.getHouInfoListForEwg(params);
                        if (result.get("errorCode").equals("0")) {
                            Map<String,Object>map=(Map<String,Object>)result.get("result");
                            //市场部的房源列表
                            List<Map<String,Object>> mktlist=(List<Map<String,Object>>)map.get("dataList");
                            for (Map<String,Object> giomap : list){
                                for (Map<String,Object> mktmap : mktlist) {
                                    if (MapUtils.getString(giomap, "HouId").equals(MapUtils.getString(mktmap, "HouId"))) {
                                        giomap.remove("HouId",null);
                                        giomap.remove("HouInfoId",null);
                                        mktmap.putAll(giomap);
                                        gmioList.add(mktmap);
                                    }
                                }
                            }
                            map.put("dataList",gmioList);
                        }
                    }else{//如果没有录入的时候
                        result=pageUtils.getJsonResult(new ArrayList<Map<String,Object>>(), params, 0);
                    }
                }else{//查询未录入
                    System.out.println("参数:"+num);
                    //查询运营部的电表录入记录
                    List<Map<String,Object>> list=seEleMeterMapper.getEleMeterList(params);
                    List<String> widList=new ArrayList<String>();
                    for (Map<String,Object> eleMap:list){
                        if(eleMap.get("HouId")!=null){
                            widList.add(eleMap.get("HouId").toString());
                        }
                    }
                    params.put("widList",widList);
                    //查询市场部的房源详表信息
                    result=zpcMktFeign.getHouInfoListForEwg(params);
                }
            }
        }
        return result;
    }

    /**
     * 新增电表录入记录
     *
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addEleMeter(Map<String, Object> params) {
        Integer result=0;
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                //电表抄表编号
                String UUID="";
                //电表抄表批次编号
                String UUID2="";
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "ElemeId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_ele_meter");
                }});
                System.out.println("uuid:"+uuid);
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("Recorder",ContextUtils.getUserId());// 电表记录人编号
                params.put("IfGenerate",1);//是否生成账单  0.未生成  1.已生成',
                params.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("GenerateTime",params.get("instm"));//账单生成日期
                List<Map<String,Object>> listMap=(List<Map<String,Object>>)params.get("data");
                Map<String,Object> tmap=new HashMap<String,Object>();//用来存放账单金额的map
                if (listMap!=null){
                    int numb=0;
                    for (Map<String,Object> map: listMap){
                        int number=0;
                        if(uuid!=null &&(!uuid.get("uuid").toString().equals(""))){
                            number=Integer.valueOf(uuid.get("uuid").toString());
                            UUID= ComUtils.getLocalTrmSeqNum("em"+numb,number);
                        }else{
                            UUID=ComUtils.getLocalTrmSeqNum("em"+numb,0);
                        }
                        UUID2=ComUtils.getLocalTrmSeqNum("ba"+numb,number);
                        map.put("BatchId",UUID2);//电表抄表批次编号
                        map.put("ElemeId",UUID);//电表抄表编号
                        map.putAll(params);
                        map.put("IfOperaType",2);//是否是整租 0否 1是 2（秘书抄表）
                        System.out.println("新增的参数:"+map);
                        seEleMeterMapper.addEleMeter(map);
                        map.put("Source",UUID);
                        numb++;
                    }
                    //账单编号
                    Map<String,Object>uuid2=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "BiId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_tenant_bill");
                    }});
                    //账单支出编号
                    String UUID3="";
                    Map<String,Object>uuid3=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "BiOutId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_bill_outlay");
                    }});
                    tmap.put("by", ContextUtils.getUserId());//操作人
                    tmap.put("BiType",2);// 1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                    tmap.put("PubType",2);//1.水费  2.电费  3.燃气',
                    tmap.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是,
                    tmap.put("CreateType","2");//房源详表
                    tmap.put("Create",ContextUtils.getUserId());//账单创建人
                    tmap.put("Status",1);//账单状态   1.待支付  2.支付完成
                    tmap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    tmap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(tmap);
                    tmap.put("BiGenerated",tmap.get("instm"));//账单生成日
                    tmap.put("ExpTime",tmap.get("instm"));//账单逾期开始时间
                    Calendar now = Calendar.getInstance();
                    int month= (now.get(Calendar.MONTH) + 1);
                    int num=0;
                    for (Map<String,Object> map: listMap){
                        if(uuid2!=null &&(!uuid2.get("uuid").toString().equals(""))){
                            int number=Integer.valueOf(uuid2.get("uuid").toString());
                            UUID= ComUtils.getLocalTrmSeqNum("tb"+num,number);
                        }else{
                            UUID=ComUtils.getLocalTrmSeqNum("tb"+num,0);
                        }
                        if(uuid3!=null &&(!uuid3.get("uuid").toString().equals(""))){
                            int number=Integer.valueOf(uuid3.get("uuid").toString());
                            UUID3= ComUtils.getLocalTrmSeqNum("zdzc"+num,number);
                        }else{
                            UUID3=ComUtils.getLocalTrmSeqNum("zdzc"+num,0);
                        }
                        if (map.get("TenId")==null){
                            map.put("TenId","TE-201903050004");
                        }
                        System.out.println("uuid3:"+uuid3);
                        System.out.println("UUID3:"+UUID3);
                        map.putAll(tmap);
                        //支出账单参数
                        map.put("StartTime",map.get("StaTime"));//账单开始时间
                        map.put("EndTime",map.get("EndTime"));//账单结束时间
                        //收入账单参数
                        map.put("BiGenerated",map.get("StaTime"));//账单开始时间
                        map.put("EndTime",map.get("EndTime"));//账单结束时间
                        map.put("LateDay",map.get("EndTime"));//账单最晚付款日
                        map.put("BiMoney",map.get("BillMoney"));//账单金额
                        map.put("BiId",UUID);
                        map.put("LateDay",map.get("EndTime"));
                        map.put("BiName",month+"月份电费账单");
                        map.put("BillExplain","电费:"+map.get("BiMoney"));
                      // map.putAll(tmap);
                        if (map.get("ProOperaType").toString().equals("2")) {//租赁类型（1.合租 2.整租）
                            seTenantBillMapper.addTenantBill(map);
                        }
                        //支出账单
                        map.put("Relation",map.get("ElemeId"));//来源编号
                        map.put("BiOutId",UUID3);
                        map.put("BiOutName",month+"月份电费账单");
                        map.put("BiOutType","4");//账单类型  1.业主(业主合同)   2.供应商  3.退租   4.公共事业费
                        map.put("StemType","2");//支出类型   1.业主  2.供应商  3.租客
                        map.put("StemId",map.get("MoviesMark"));//支出关联人编号，根据支出类型
                        System.out.println("map:"+map);
                        seBillOutlayMapper.addSeBillOutlay(map);
                        num++;
                    }
                    result=1;
                }else{
                    result=0;
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 账单管理查询每间房的水电燃账单列表
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> getWegList(Map<String, Object> params) {
        return seEleMeterMapper.getWegList(params);
    }

    /**
     * 账单管理查询每间房的水电燃账单总数
     * @param params
     * @return
     */
    @Override
    public Integer getWegListCount(Map<String, Object> params) {
        return seEleMeterMapper.getWegListCount(params);
    }
}
